package com.stu.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.stu.mall.auth.feign.MemberFeignService;
import com.stu.mall.auth.vo.SocialUser;
import com.stu.mall.common.constant.AuthServerConstant;
import com.stu.mall.common.utils.HttpUtils;
import com.stu.mall.common.utils.R;
import com.stu.mall.common.vo.MemberResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@Slf4j
public class OAuth2Controller {


    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session, HttpServletResponse httpServletResponse) throws Exception {

        Map<String, String> map = new HashMap<>();
        map.put("client_id", "652483759");
        map.put("client_secret", "cc205345290b1b5cfcdaecb98accb355");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gmall.com/oauth2.0/weibo/success");
        map.put("code", code);

        //1.根据Code换取Access Token
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());

        //2.处理
        if (response.getStatusLine().getStatusCode() == 200) {
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            //知道当前是哪个社交用户
            //1)。当前用户如果是第一次进网站，自动注册进来，需要为该账号生成系统内的账号
            log.info("登录后用code换取的token值：" + socialUser.getAccess_token());
            //调用远程服务
            R oauthLogin = memberFeignService.oauthLogin(socialUser);
            if (oauthLogin.getCode() == 0) {
                MemberResponseVo memberResponseVo = oauthLogin.getData("data", new TypeReference<MemberResponseVo>() {
                });
                log.info("登录成功：用户信息：\n{}", memberResponseVo.toString());


                //用户信息保存session
                //默认发送的sessioon令牌是当前域，子域无法使用
                session.setAttribute(AuthServerConstant.LOGIN_USER, memberResponseVo);

                return "redirect:http://gmall.com";
            } else {
                return "redirect:http://auth.gmall.com/login.html";
            }

        } else {
            return "redirect:http://auth.gmall.com/login.html";
        }

    }
}
